package main

import (
	"fmt"
	"os"
)

func readMaze(filename string) [][]int{
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	var row,col int
	fmt.Fscanf(file,"%d %d",&row,&col)
	maze := make([][]int,row)

	for i:= range maze {
		maze[i] = make([]int,col)
		for j:= range maze[i]{
			fmt.Fscanf(file,"%d",&maze[i][j])
		}
	}

	return maze

}


type point struct {
	i,j int
}

// 声明探索方向的坐标(上左下右)
var dirs = [4]point{
	{-1,0},{0,-1},{1,0},{0,1},
}

func (p point) add(r point) point {
	return point{p.i+r.i,p.j+r.j}
}

// 获取指定点在表格中的位置，以及是否越界
func (p point) at(grid [][]int) (int,bool) {
	// 行越界
	if p.i < 0 || p.i>=len(grid){
		return 0,false
	}
	// 列越界
	if p.j < 0 || p.j>= len(grid[p.i]){
		return 0,false
	}
	return grid[p.i][p.j],true
}

func work(maze [][]int,start ,end point) ([][]int,bool) {
	steps := make([][]int,len(maze))
	// 初始化steps
	for i:= range steps {
		steps[i] = make([]int,len(maze[i]))
	}

	flag := false
	// 用来存储探索到的节点
	Q := []point{start}
	// 当Q为空时说明探索完毕
	for len(Q)>0 && !flag{
		cur := Q[0]
		Q = Q[1:]

		// 表示探索到了
		if cur.i== end.i && cur.j == end.j{
			flag = true
			break
		}
		for _,dir := range dirs{
			// 探索路径
			next:=cur.add(dir)
			val, ok := next.at(maze)
			if !ok || val == 1{
				continue
			}
			// 判断是否又走回去了
			val,ok = next.at(steps)
			if !ok || val != 0{
				continue
			}

			if next.i == end.i && next.j == end.j{
				flag = true
				break
			}
			curStep,_ := cur.at(steps)
			steps[next.i][next.j] = curStep + 1

			Q = append(Q,next)
		}

	}

	return steps,flag
}

func main() {
	maze := readMaze("maze/maze.in")
	for _,row := range maze{
		for _,val := range row{
			fmt.Printf("%d ",val)
		}
		fmt.Println()
	}
	fmt.Println("走完迷宫之后……")
	steps,flag := work(maze,point{0,0},point{len(maze)-1,len(maze[0])-1})
	if flag{
		fmt.Println("找到路径")
	}else{
		fmt.Println("没有找到路径")

	}
	for _,row := range steps{
		for _,val := range row{
			fmt.Printf("%3d ",val)
		}
		fmt.Println()
	}

}
